package com.oswift.cms.web.backstage;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.FriendSiteBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.service.IFriendSiteService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class FriendSiteAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(FriendSiteAction.class);

    /**
     * FriendSiteServiceImpl注入对象
     */
    @Resource
    private IFriendSiteService friendSiteService;

    /**
     * ChannelServiceImpl注入对象
     */
    @Resource
    private IChannelService channelService;

    /**
     *
     * 跳转到添加友情链接页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddFriendSite", method = RequestMethod.GET)
    public ModelAndView loadAddFriendSite(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = friendSiteService.loadAddFriendSite(PageName.FRIENDSITE,
                    companyId);
            mv.addObject(METHOD, METHOD_ADD);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddFriendSite is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddFriendSite is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 跳转到修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateFriendSite", method = RequestMethod.GET)
    public ModelAndView loadUpdateFriendSite(@RequestParam("id")
    int id)
    {
        ModelAndView mv = null;
        try
        {
            if (id > 0)
            {
                mv = new ModelAndView(PageName.FRIENDSITE);
                FriendSiteBean bean = friendSiteService.getFriendSiteDetail(id);
                mv.addObject(METHOD, METHOD_UPDATE);
                mv.addObject("bean", bean);
                if (null == bean.getUpdateTime())
                {
                    bean
                            .setUpdateTime(TimeUtil
                                    .getCurTimeByFormat(TimeUtil.ISO_DATE_NOSECOND_FORMAT));
                }
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                bean.setUrl("getFriendSiteList");
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Get loadUpdateFriendSite page is error.id=" + id, e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getFriendSiteList");
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 添加友情链接信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addFriendSite", method = RequestMethod.POST)
    @ResponseBody
    public Object addFriendSite(HttpServletRequest request, FriendSiteBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(bean.getTitle())
                    || StringUtil.isEmpty(bean.getSiteUrl())
                    || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            AdminBean adminBean = this.getAdmin(request);
            bean.setCompanyId(adminBean.getCompanyID());
            bean.setTableName(Field.TableName.FRIENDSITE);
            bean.setInputer(adminBean.getAdminName());

            boolean isSuccess = friendSiteService.save(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.FRIENDSITE_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.FRIENDSITE_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.FRIENDSITE_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to save FriendSite info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 获取公共内容信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getFriendSiteList", method = RequestMethod.GET)
    public ModelAndView getFriendSiteList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String orderField = request.getParameter("orderField");
            String orderType = request.getParameter("orderType");
            String s_Status = request.getParameter("status");
            String s_ChannelId = request.getParameter("channelId");
            String searchType = request.getParameter("searchType");
            String keyword = request.getParameter("keyword");
            String s_PageNum = request.getParameter("pageNum");

            int status = Field.Status.ALL;
            if (!StringUtil.isEmpty(s_Status))
            {
                status = Integer.valueOf(s_Status);
            }
            int channelId = -1;
            if (!StringUtil.isEmpty(s_ChannelId))
            {
                channelId = Integer.valueOf(s_ChannelId);
            }
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(s_PageNum))
            {
                pageNum = Integer.valueOf(s_PageNum);
            }

            // 权限判断
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<CommonModelBean> bean = friendSiteService.getCommonModel(orderField,
                    orderType, status, channelId, searchType, keyword,
                    this.pageRecordNum, pageNum, Field.TableName.FRIENDSITE,
                    companyId);

            // 获取包含文章板块的栏目
            DictionaryBean dictionaryBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_FRIENDSITE_KEY);
            List<ChannelBean> channelList = channelService.getChannelList2(
                    companyId, dictionaryBean.getFieldValue());

            mv = new ModelAndView(PageName.FRIENDSITELIST);
            mv.addObject("pageBean", bean);
            mv.addObject("status", status);
            mv.addObject("channels", channelList);
            mv.addObject("orderType", orderField + "_" +orderType);
            mv.addObject("channelId", channelId);
        }
        catch (PlatException e)
        {
            log.error("Get FriendSiteList info is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getFriendSiteList.html");
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 修改状态信息
     *
     * @author zhuou
     *
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object updateStatus(@RequestParam("status")
    String status, @RequestParam("ids")
    String ids)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(status) || StringUtil.isEmpty(ids))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            boolean isSuccess = friendSiteService.updateStatus(status, ids);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.UPDATE_STATUS_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.UPDATE_STATUS_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.UPDATE_STATUS_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to updateStatus error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 友情链接详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/friendSiteDetail", method = RequestMethod.GET)
    public ModelAndView friendSiteDetail(@RequestParam("id")
    int id)
    {
        ModelAndView mv = null;
        try
        {
            if (id > 0)
            {
                mv = new ModelAndView(PageName.FRIENDSITEDETAIL);
                FriendSiteBean bean = friendSiteService.getFriendSiteDetail(id);
                mv.addObject("bean", bean);
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                bean.setUrl("getFriendSiteList");
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Get friendSiteDetail page is error.id=" + id, e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            bean.setUrl("getFriendSiteList");
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 修改友情链接
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updateFriendSite", method = RequestMethod.POST)
    @ResponseBody
    public Object updateFriendSite(FriendSiteBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (bean.getCommonModelId() <= 0)
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getTitle()) || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            boolean isSuccess = friendSiteService.update(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.FRIENDSITE_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.FRIENDSITE_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.FRIENDSITE_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updateFriendSite is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updateFriendSite is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 删除友情链接
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delFriendSite", method = RequestMethod.POST)
    @ResponseBody
    public Object delFriendSite(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("ids");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            int delSuccessNum = 0;
            int delFailNum = 0;
            String[] array = id.split(Field.COMMA);
            for (String i : array)
            {
                boolean isSuccess = friendSiteService
                        .delete(Integer.valueOf(i));
                if (isSuccess)
                {
                    delSuccessNum++;
                }
                else
                {
                    delFailNum++;
                }
            }

            if (delSuccessNum == array.length)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.FRIENDSITE_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.FRIENDSITE_DEL_FAIL);
                String mess = ResourceManager
                        .getValue(PageCode.FRIENDSITE_DEL_FAIL);
                messBean.setContent(StringUtil.replace(mess, String
                        .valueOf(delSuccessNum), String.valueOf(delFailNum)));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delFriendSite is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delFriendSite is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    public void setFriendSiteService(IFriendSiteService friendSiteService)
    {
        this.friendSiteService = friendSiteService;
    }

    public void setChannelService(IChannelService channelService)
    {
        this.channelService = channelService;
    }
}
